/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.util.log.output;

import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * CustomizedFormatter : The customized JUL formatter.
 * 
 * @author Romain DUBOIS
 */
public class CustomizedFormatter extends Formatter {

    /** The format to use */
    private final String mFormat;
    /** The platform end of line */
    private final String mEol;

    /**
     * Constructor
     * 
     * @param pFormat
     *            The format to use
     * @param pEol
     *            The platform End Of Line
     */
    public CustomizedFormatter(final String pFormat, final String pEol) {
        super();
        mFormat = pFormat;
        mEol = pEol;
    }

    /**
     * {@inheritDoc}
     * 
     * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
     */
    @Override
    public String format(final LogRecord pRecord) {
        // Main line
        final Date lDate = new Date(pRecord.getMillis());
        final StringBuilder lBuilder = new StringBuilder();
        lBuilder.append(String.format(mFormat, pRecord.getLevel().getLocalizedName(),
                pRecord.getLoggerName(), lDate, Long.valueOf(pRecord.getMillis()),
                pRecord.getSourceClassName(), pRecord.getSourceMethodName(), pRecord.getMessage()));
        lBuilder.append(mEol);

        // Exception (if any)
        if (pRecord.getThrown() != null) {
            lBuilder.append(pRecord.getThrown().getLocalizedMessage()).append(mEol);
            for (final StackTraceElement lElement : pRecord.getThrown().getStackTrace()) {
                lBuilder.append('\t').append(lElement.toString()).append(mEol);
            }
        }

        return lBuilder.toString();
    }

}
